package cn.easy.mortgage.api;

import cn.easy.base.bean.common.ApiResultBean;
import cn.easy.base.utils.BaseUtils;
import cn.easy.mobile.utils.ValidateUtil;
import cn.easy.mobile.web.ApiBaseController;
import cn.easy.mortgage.bean.*;
import cn.easy.mortgage.domain.Channel;
import cn.easy.mortgage.domain.EstateEvalInfo;
import cn.easy.mortgage.domain.LoanRequest;
import cn.easy.mortgage.service.*;
import cn.easy.mortgage.utils.Constants;
import cn.easy.mortgage.utils.ProjectUtil;
import cn.easy.mortgage.utils.SmsUtils;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.text.TextValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/mtg")
public class ApiMtgController extends ApiBaseController {
    @Autowired
    private HjPgService hjPgService;
    @Autowired
    private EstateEvalInfoService estateEvalInfoService;
    @Autowired
    private LoanRequestService loanRequestService;
    @Autowired
    private LvXinTongSmsService lvXinTongSmsService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ChannelService channelService;

    @RequestMapping(value = "/getCode", method = RequestMethod.POST)
    @ResponseBody
    ApiResultBean<? extends Object> getCode(String mobile, HttpServletRequest request, HttpServletResponse response) {
        ValidateUtil.checkExpire(SmsUtils.CODE_MAP, 1800);
        if (!TextValidator.isMobileSimple(mobile)) {
            return toError("手机号格式不正确", 101);
        }
        if (!ValidateUtil.validCodeSendInterval(SmsUtils.CODE_MAP, mobile, 60)) {
            return toError("验证码已发送，请60秒后重新获取", 102);
        }
        if (!SmsUtils.checkSafe(mobile)) {
            return toError("发送频繁请稍后再试", 103);
        }
        try {
            lvXinTongSmsService.sendCode(SmsUtils.CODE_MAP, mobile, getConfigStr(Constants.CODE_NOTICE_TEMPLATE_KEY));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
        return toSuccess("验证码已发送");
    }

    @RequestMapping(value = "/toEval", method = RequestMethod.POST)
    @ResponseBody
    ApiResultBean<? extends Object> toEval(HjPGSingleQueryBean hjPGSingleQueryBean, String mobile, String code, String regCode, Model model, HttpServletRequest request) {
        if (!BaseUtils.isDev() && !ValidateUtil.checkCode(SmsUtils.CODE_MAP, mobile, code, 900, true)) {
            return toError("验证码无效", -1);
        }
        EstateEvalInfo estateEvalInfo = null;
        if (!estateEvalInfoService.evaluatedOnToday(hjPGSingleQueryBean.getHouseAddress(), hjPGSingleQueryBean.getRoomSize())) {
            HjPGSingleQueryResultBean hjPGSingleQueryResultBean = hjPgService.singleQuery(hjPGSingleQueryBean);
            if (hjPGSingleQueryResultBean == null || StringUtils.isBlank(hjPGSingleQueryResultBean.getFv_house_total_price())) {
                return toError("未查询到评估价格", -1);
            }
            estateEvalInfo = estateEvalInfoService.valueOf(regCode, hjPGSingleQueryBean, hjPGSingleQueryResultBean);
            estateEvalInfo = estateEvalInfoService.save(estateEvalInfo);
        } else {
            estateEvalInfo = estateEvalInfoService.findByHouseAddressAndRoomSizeOnToday(hjPGSingleQueryBean.getHouseAddress(), hjPGSingleQueryBean.getRoomSize());
        }
        LoanRequest loanRequest = LoanRequest.valueOfMiniApp(regCode, mobile, estateEvalInfo, getChannel(request));
        loanRequestService.save(loanRequest);
        Map<String, String> result = new HashMap<>();
        result.put("id", estateEvalInfo.getId());
        result.put("loanRequestId", loanRequest.getId());
        return toSuccess("查询成功", result);
    }

    @RequestMapping(value = "/getAreas", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean<? extends Object> getAreas(HttpServletRequest request, String parentCode, String codeType) {
        return toSuccess("查询成功", commonService.getAreaList());
    }

    @RequestMapping(value = "/getPropertyType", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultBean<? extends Object> getPropertyType(HttpServletRequest request) {
        List<SelectBean> result = new ArrayList<>();
        for (Map.Entry<String, String> entry : getConfigMap(Constants.PROPERTY_TYPE_KEY).entrySet()) {
            result.add(new SelectBean(entry.getValue(), entry.getKey()));
        }
        return toSuccess("查询成功", result);
    }

    @RequestMapping(value = "/getHouseAddress", method = RequestMethod.GET)
    @ResponseBody
    ApiResultBean<? extends Object> gethouseAddress(HttpServletRequest request, String regCode, String propertyType, String addr) {
        HjPGSearchHouseBean hjPGSearchHouseBean = new HjPGSearchHouseBean(addr, propertyType, regCode);
        HjPGSearchHouseResultBean hjPGSearchHouseResultBean = hjPgService.searchHouse(hjPGSearchHouseBean);
        return toSuccess("查询成功", hjPGSearchHouseResultBean.getSingleQueryBeanList());
    }

    @RequestMapping(value = "/getEvalInfo", method = RequestMethod.GET)
    @ResponseBody
    ApiResultBean<? extends Object> getEvalInfo(HttpServletRequest request, String id, String loanRequestId) {
        EstateEvalInfo estateEvalInfo = estateEvalInfoService.getOne(id);
        Map<String, Object> data = new HashMap<>();
        data.put("loanAmount", ProjectUtil.calLoanAmount(estateEvalInfo));
        data.put("estateEvalInfo", estateEvalInfo);
        data.put("loanRequestId", loanRequestId);
        return toSuccess("查询成功", data);
    }

    @RequestMapping(value = "/getLoanRequest", method = RequestMethod.GET)
    @ResponseBody
    ApiResultBean<? extends Object> getLoanRequest(HttpServletRequest request, String loanRequestId) {
        LoanRequest loanRequest = loanRequestService.getOne(loanRequestId);
        EstateEvalInfo estateEvalInfo = estateEvalInfoService.getOne(loanRequest.getEstateEvalId());

        Map<String, Object> data = new HashMap<>();
        data.put("loanAmount", ProjectUtil.calLoanAmount(estateEvalInfo));
        data.put("loanRequest", loanRequest);
        return toSuccess("查询成功", data);
    }

    @RequestMapping(value = "/toRequest", method = RequestMethod.POST)
    @ResponseBody
    ApiResultBean<? extends Object> toRequest(LoanRequest loanRequest) {
        if (!TextValidator.isMobileExact(loanRequest.getMobile())) {
            return toError("手机号格式不正确", -1);
        }
        LoanRequest loanRequestDb = loanRequestService.getOne(loanRequest.getId());
        loanRequestDb.setStatus(Constants.REQUEST_STATUS_SUBMIT);
        loanRequestDb.setLoanAmount(loanRequest.getLoanAmount());
        loanRequestDb.setName(loanRequest.getName());
        loanRequestDb.setRemark(loanRequest.getRemark());
        loanRequestDb.setMobile(loanRequest.getMobile());
        loanRequestService.save(loanRequestDb);
        return toSuccess("提交成功");
    }

    private String getChannelId(HttpServletRequest request) {
        Channel channel = getChannel(request);
        return channel == null ? null : channel.getId();
    }

    private Channel getChannel(HttpServletRequest request) {
        String code = request.getParameter("channel");
        if (StringUtils.isBlank(code)) {
            return null;
        }
        Channel channel = channelService.findByCode(code);
        return channel;
    }
}
